#!/usr/bin/env python3
import asyncio
import websockets
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def handler(websocket, path):
    logger.info(f"新客户端连接: {websocket.remote_address}")
    try:
        async for message in websocket:
            logger.info(f"收到消息: {message}")
            # 简单回显
            response = f"服务器收到: {message}"
            await websocket.send(response)
            logger.info(f"发送响应: {response}")
    except websockets.exceptions.ConnectionClosed:
        logger.info("连接关闭")
    except Exception as e:
        logger.error(f"处理消息时出错: {e}")

async def main():
    host = "0.0.0.0"
    port = 8080
    logger.info(f"启动简单WebSocket服务器: ws://{host}:{port}")
    
    async with websockets.serve(handler, host, port):
        logger.info("服务器启动成功，等待连接...")
        await asyncio.Future()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("服务器停止")
    except Exception as e:
        logger.error(f"服务器运行出错: {e}") 